#!python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, url_for, render_template, send_from_directory,  \
    current_app, redirect
import json
import pymysql
from werkzeug import secure_filename
import os
import time
import urlparse
from .admin import login_required
from .db import get_db

movie_list = Blueprint("movie_list", __name__)

@movie_list.route("/list", methods = ["GET", "POST"])
def get_list():
    conn=get_db()

    args = request.values
    perm = int(args.get("perm", 0))
    start = int(args.get("start", 0))
    count = int(args.get("count", 10))

    # download_url
    download_url = args.get("download_url", u"")

    # movie_name
    movie_name = args.get("movie_name", u"")

    # catalog
    catalog=args.get("catalog", u"")

    # encrypted name
    enc_name = args.get("enc_name", u"")

    # sql
    sql = u"""select
        id,name,description,download_link,download_password,add_time,size,
        file_owner,catalog,img_url
        from video where permission <= %d and state > 0""" % perm

    if movie_name:
        sql += u" and name = '%s' and download_link is not null limit %d,%d" % (pymysql.escape_string(movie_name), start, count)
    elif enc_name:
        sql += u" and name = '%s'" % (enc_name,)
    elif download_url:
        sql +=  u" and download_link = '%s'" % pymysql.escape_string(download_url)
    elif catalog:
        sql += u" and catalog = '%s' and download_link is not null order by add_time desc limit %d,%d" % (pymysql.escape_string(catalog), start, count)
    else:
        sql += u" and download_link is not null order by add_time desc limit %d, %d" % (start, count)
    current_app.logger.debug(sql)
    cur = conn.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    cur.close()

    data = []
    for row in result:
        url = row[9]
        if url and url.startswith("/"):
            u = urlparse.urlparse(request.url)
            url =u"%s://%s%s" % (u.scheme, u.netloc, url)
        data.append(
            dict(
                id = row[0],
                name = row[1],
                description = row[2],
                download_link = row[3],
                download_password = row[4],
                add_time = row[5].strftime("%Y-%m-%d %H:%M:%S"),
                size = row[6],
                file_owner = row[7],
                catalog = row[8],
                img_url = url
            )
        )

    return json.dumps(data),200,{"Content-Type":"application/json"}

@movie_list.route("/show")
@login_required
def show():
    sql = """select
    id,name,description,download_link,download_password,add_time,
    size,file_owner,permission,catalog,state,img_url
    from video 
    where 1
        order by add_time desc limit 20
        """
    conn = get_db()
    cur=conn.cursor()
    cur.execute(sql)
    rs = cur.fetchall()
    cur.close()

    return render_template("movie_list.html", movies = rs)

@movie_list.route("/edit/<id>", methods=["GET", "POST"])
def edit(id =0):
    return "/edit/<id>"

def allowed_filename(filename):
    return "." in filename and \
            filename.rsplit(".", 1)[1] in current_app.config.get("ALLOWED_EXTENSIONS")

@movie_list.route("/add", methods=["GET", "POST"])
@login_required
def add():
    if request.method == "POST":
        movie_name = pymysql.escape_string(request.form.get("movie_name",""))
        desc = pymysql.escape_string(request.form.get("desc",""))
        download_link = pymysql.escape_string(request.form.get("download_link",""))
        download_password=pymysql.escape_string(request.form.get("download_password",""))
        size = pymysql.escape_string(request.form.get("size",""))
        catalog = pymysql.escape_string(request.form.get("catalog",""))
        img_url = pymysql.escape_string(request.form.get("img_url",""))
        if not movie_name or not download_link:
            err_msg = u"必须填写电影名称或下载链接!"
            return render_template("add_resource_fail.html", err_msg = err_msg), 400
        f = request.files["img"]
        if f:
            if allowed_filename(f.filename):
                filename = secure_filename(f.filename)
                t = time.time()
                filename = u"%d_%s" % (t, filename)
                f.save(os.path.join(current_app.config.get("UPLOAD_FOLDER"), filename))
                img_url = url_for(".uploaded_file", filename=filename)
            else:
                err_msg = u"非法的文件类型, 只有如下文件类型被允许:<br />&nbsp;&nbsp;%s" % (
                        ",".join(current_app.config.get("ALLOWED_EXTENSIONS")), )
                return render_template("add_resource_fail.html", err_msg = err_msg), 400
        conn = get_db()
        cur = conn.cursor()
        sql = u"""insert into video (
            name,description,download_link,
            download_password,add_time,size,catalog,img_url
        ) values(
            '{movie_name}','{desc}','{download_link}','{download_password}',
            now(),'{size}','{catalog}','{img_url}'
        )
        """.format(**locals())
        cur.execute(sql)
        conn.commit()
        return  render_template("add_resource_success.html")

    return render_template("add_resource.html")


@movie_list.route("/del/<id>")
@login_required
def delete(id=0):
    sql = "delete from video where id = '%s'"  % pymysql.escape_string(id)
    conn = get_db()
    cur=conn.cursor()
    cur.execute(sql)
    cur.close()
    return redirect(url_for(".show"))

@movie_list.route("/uploads/<filename>")
def uploaded_file(filename):
    return send_from_directory(current_app.config["UPLOAD_FOLDER"],
            filename)
